package com.kancy.springcloudconfig.util;

import com.kancy.springcloudconfig.constants.Constants;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

public class JasyptUtil {
    public static String DEFAULT_TEMPLATE = "ENC(%s)";

    public static String encrypt(String data,String password){
        StringEncryptor encryptor = getStringEncryptor(password);
        return encryptor.encrypt(data);
    }

    public static String encrypt(String data){
        return encrypt(data, Constants.DEFAULT_JASYPT_PASSWORD);
    }

    public static String decrypt(String data,String password){
        if(data != null && data.startsWith("ENC(") && data.endsWith(")")){
            data = data.substring(4, data.length() -1);
        }
        StringEncryptor encryptor = getStringEncryptor(password);
        return encryptor.decrypt(data);
    }

    public static String decrypt(String data){
        return decrypt(data, Constants.DEFAULT_JASYPT_PASSWORD);
    }

    private static StringEncryptor getStringEncryptor(String password){
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }

    public static String format(String result){
        return String.format(DEFAULT_TEMPLATE, result);
    }

}
